package com.chinaums.open.api.internal.util.converter;

import com.chinaums.open.api.OpenApiException;
import com.chinaums.open.api.OpenApiResponse;
import com.chinaums.open.api.internal.util.FieldUtils;
import net.sf.json.JSONObject;

import java.lang.reflect.Field;
import java.text.ParseException;

/**
 * Created with IntelliJ IDEA.
 * User: ZHANGWEI
 * Date: 2016/12/2
 * Time: 14:50
 * 所属模块：
 * 功能说明：
 */
public class JsonConverter implements Converter {
    public <T extends OpenApiResponse> T toResponse(String paramString, Class<T> paramClass) throws OpenApiException, IllegalAccessException, InstantiationException, ParseException, ClassNotFoundException {
        JSONObject jsonObj = JSONObject.fromObject(paramString);
        Object bean = paramClass.newInstance();
        for (Class clazz = bean.getClass(); !clazz.getName().equals(
                Object.class.getName()); clazz = clazz.getSuperclass()) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                String name = fieldName;
                String key = fieldName;
                String value = jsonObj.get(key) == null ? null : jsonObj
                        .get(key).toString().trim();
                FieldUtils.setFieldValueByTypeAndFormat(field, bean, value, null);
            }
        }
        return (T) bean;
    }
}
